const {request} = require("../utils/request");
const {extractCookieValues, md5} = require("../utils/fun");
const {Builder, By, Key, until} = require('selenium-webdriver');
const Device = require("../utils/device");
require('chromedriver');


const ACCESS_KEY = "yWpx3hWQHFhSnTCj#{}#6KuRKuaAjLJ5sYRy"


class LoginBo {
    userModel = null
    gameModel = null

    constructor(userModel, gameModel) {
        this.userModel = userModel
        this.gameModel = gameModel
        this.initDevice()
    }

    initDevice(){
        this.device = new Device()
    }


    async doLoginToGame() {

        let now = new Date().getTime().toString()
        let sign_str = ACCESS_KEY.replace("{}", this.gameModel['game_id']) + now

        let sign = md5(sign_str)

        let data = {
            uname: this.userModel['username'],
            pwd: this.userModel['password'],
            memory: "4040992",
            device_model: this.device.deviceinfo['model'],
            app_version: "1.0.0",
            sign: sign,
            processor_model: this.device.deviceinfo['processor_model'],
            do: "login",
            type: "1",
            uuid: this.device.deviceinfo['oaid'],
            resolution: "1080x1920",
            platform: "GR",
            cpu_count: "4",
            network: "wifi",
            cpu_max_frequency: "2865.60",
            remain_disk_size: "16963280",
            siteid: this.gameModel['site_id'],
            model: "PCLM10",
            remain_memory: "3537196",
            oaid: "null_gaore_null",
            agentid: this.gameModel['agent_id'],
            device_id: this.device.deviceinfo['oaid'],
            electric: "0",
            disk_size: "18060052",
            baseband: "",
            version: "1.0.0",
            system: "9",
            device_brand: this.device.deviceinfo.baseband,
            appid: this.gameModel['game_id'],
            channelID: "1",
            time: now
        }

        let _data = new URLSearchParams(data).toString();

        let response = await request({
            url: "/user/sdk_passport.php",
            method: 'post',
            responseType: 'json',
            data: _data,
            baseURL: this.gameModel['domain'],
            original: true
        })

        let result = response.data

        if (result.ret === 1) {
            let cookies = response.headers.get('Set-Cookie');
            let cookiesArr = extractCookieValues(cookies)
            let loginInfo = {
                uid: result.uid,
                sessionid: result.sessionid,
                loginreg: cookiesArr['loginreg'],
            }

            this.userModel.login_info = JSON.stringify(loginInfo)

            this.userModel.save()
            return true
        }
        console.log(result)
        return false
    }


    async getUserInfo() {
        if (this.userModel.role_info) {
            return true
        }
        let loginInfo = this.userModel.login_fmt_info
        let uid = loginInfo.uid
        let username = this.userModel['username']
        let sessionid = loginInfo.sessionid

        let url = this.gameModel['domain'] + "/h5/login_skip.php?uid=" + uid + "&uname=" + username + "&appid=" + this.gameModel['game_id'] + "&sessionid=" + sessionid + "&gameversion=1.0.0&logotype=" + this.gameModel['game_id'] + "&uuid=66eddbf095bb265c-null&oaid=null_gaore_null"


        let userInfo = {}

        if (this.gameModel['type'] === "tanwan") {
            userInfo = await this.parseTanWanUserInfo(url)
        } else {
            userInfo = await this.parseUserInfo(url)
        }
        if (Object.keys(userInfo).length > 0) {

            let device = this.device
            userInfo['client_ip'] = device['client_ip']
            this.userModel.role_info = JSON.stringify(userInfo)
            this.userModel.device = JSON.stringify(device['deviceinfo'])
            this.userModel.save()
            return true
        }
        return false
    }

    async parseUserInfo(url) {
        let userinfo = {};
        const driver = await new Builder().forBrowser('chrome').build();
        const timeout = 10000;
        const pollTimeout = 1000;

        try {
            await driver.get(url)

            await driver.wait(until.elementLocated(By.css('#gameFrame>iframe[name="game"]')), timeout);

            const iframe = await driver.findElement(By.xpath("//iframe[@name='game']"));

            await driver.switchTo().frame(iframe);
            await driver.wait(until.elementLocated(By.css('#egret-player')), timeout);

            await driver.wait(until.elementLocated(By.xpath("//div[@id='egret-player']")), timeout);
            await driver.sleep(5000);
            await driver.executeScript(`
        let item = LoadingLayer.instance.$children[1].$children[3];
        item.dispatchEvent(new egret.TouchEvent(egret.TouchEvent.TOUCH_TAP));
    `);

            // 切回默认上下文
            await driver.switchTo().defaultContent();


            while (true) {
                userinfo = await driver.executeScript('return window.userInfo');
                if (Object.keys(userinfo).length > 0) {
                    //console.log(userinfo);
                    break;
                }
                await driver.sleep(1000);
            }
        } finally {
            await driver.quit();
        }

        return userinfo
    }

    async parseTanWanUserInfo(url) {
        let userinfo = {};


        const driver = await new Builder().forBrowser('chrome').build();
        const timeout = 10000;
        const pollTimeout = 1000;

        try {
            await driver.get(url)

            await driver.wait(until.elementLocated(By.css('#gameFrame>iframe[name="game"]')), timeout);
            const iframe = await driver.findElement(By.xpath("//iframe[@name='game']"));
            await driver.sleep(2000);

            await driver.switchTo().frame(iframe);

            await driver.wait(until.elementLocated(By.xpath("//div[@id='curDf']")), timeout);

            const element = await driver.findElement(By.xpath("//div[@id='curDf']/p"));

            await element.click();

            await driver.switchTo().defaultContent();


            while (true) {
                userinfo = await driver.executeScript('return window.userInfo');
                if (Object.keys(userinfo).length > 0) {
                    // console.log(userinfo);
                    break;
                }
                await driver.sleep(1000);
            }
        } finally {
           await driver.quit();
        }

        return userinfo
    }


    /**
     * 登录到抽奖中心
     */
    async doLoginToLottery() {
        if(this?.tryNum > 2){
            return
        }
        this.tryNum = this.tryNum? this.tryNum + 1 : 1
        let now = Math.floor(new Date().getTime() / 1000)
        if (!this.userModel.login_fmt_info) {
            return false
        }
        let userInfo = this.userModel.role_fmt_info

        let params = {
            gameId: userInfo['game_id'],
            serverId: userInfo['server_id'],
            roleId: userInfo['role_id'],
            userName: userInfo['user_name'],
            deviceinfo: this.userModel.device
        };


        let data = Object.assign({
            'token': this.userModel.login_fmt_info['sessionid'],
            'time': now,
            'game_id': userInfo['game_id'],
            'user_name': userInfo['user_name'] //这里的是user_name不是userName
        }, params)
        let sign_str = data['token'] + data["game_id"] + data['user_name'] + data['time'] + ACCESS_KEY.replace("{}", data['game_id'])
        data['sign'] = md5(sign_str)

        let response = await request({
            url: '/api/api.php/protocol/101001',
            method: 'post',
            responseType: 'json',
            formData: data,
            headers: {},
            original: true
        })
        if (response.data.status != 200) {

            if(response.data?.msg == "请先登录再进行操作"){
                //重试
                let ret = await this.doLoginToGame()
                if(ret){
                    return await this.doLoginToLottery()
                }
            }
            return false
        }
        let cookies = response.headers.get('Set-Cookie');
        this.userModel.cookies = cookies.join(", ")
        this.userModel.save()
        return true
    }


}


module.exports = LoginBo